package com.liyong.bos.controller;

import com.liyong.bos.domain.TUser;
import com.liyong.bos.service.StaffService;
import com.liyong.bos.utils.JsonResult;
import com.liyong.bos.utils.ValidateCode;
import com.liyong.bos.vo.TUserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by ApacheMoy on 2017/4/5.
 */
@Controller
@RequestMapping("/user")
public class StaffController {
    @Autowired
    private StaffService staffService;
    @RequestMapping("/addUser")
    public String insertUserTest(HttpServletRequest request, HttpServletResponse response){
        TUser tUser = new TUser();
        tUser.setId("5201314");
        tUser.setUsername("liyongdd");
        tUser.setPassword("8525");
        tUser.setSalary(60000.0);
        staffService.insertUser(tUser);
        return "showUser";
    }
    @RequestMapping("/login")
    public String staffLogin(){
        return "redirect:/pages/LoginPage.html";
    }
    /**
     * 取图片*/

    @RequestMapping(value = "/getValidateImg")
    public void getValidateCodeImg(HttpServletRequest request,HttpServletResponse response){
        //insertUserTest(request,response);
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        HttpSession session=request.getSession();
        ValidateCode vCode = new ValidateCode(120,40,4,100);
        session.setAttribute("code", vCode.getCode());
        try {
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ResponseBody
    @RequestMapping(value = "/checkLogin",method = RequestMethod.POST)
    public  JsonResult userLogin(TUserLoginVo tUserLoginVo, HttpServletRequest request, HttpServletResponse response){
        HttpSession session=request.getSession();
        String code= (String) session.getAttribute("code");
        JsonResult jsonResult=new JsonResult();
        if(code.equals(tUserLoginVo.getCheckcode())){
            TUser tUser=staffService.finUser(tUserLoginVo.getUsername(),tUserLoginVo.getPassword());
            if(tUser!=null){
                jsonResult.setMsg("success");
                return  jsonResult;
            }
        }
        jsonResult.setMsg("error");
        return jsonResult;

    }
}
